<template>
  <div class="m-img-upload" v-loading="loading" :style="styles">
    <div class="m-img-upload-icon"><i class="iconfont">&#xe642;</i><br/>点此上传</div>
    <input :multiple="limit==0" type="file" @change="handleChange"/>
  </div>
</template>

<script>
import axios from 'axios'
import store from '@/store'
export default {
  props: {
    value: {
      type: [String, Array]
    },
    headers: {
      type: Object,
      default () {
        return {}
      }
    },
    accept: {
      type: String,
      default: 'image/jpeg,image/png'
    },
    size: {
      type: Number,
      default: 1024 * 1024 * 5
    },
    limit: {
      type: Number,
      default: 1
    },
    formatList: {
      type: Array,
      default () {
        return ['.png', '.jpeg', '.jpg']
      }
    },
    action: {
      required: false,
      default: '/api/v1/user/upload/imageCompress'
    },
    quality: {
      type: Number,
      default: 80
    },
    width: {
      type: String
    },
    height: {
      type: String
    }
  },
  data () {
    return {
      loading: false
    }
  },
  computed: {
    styles () {
      let result = {
        width: this.width,
        height: this.height
      }
      if (this.value && this.limit === 1) {
        result['backgroundImage'] = `url(${this.value})`
      }
      return result
    }
  },
  mounted () {
    this.$$fileCount = 0
  },
  methods: {
    handleChange () {
      let self = this
      import('daycaca').then(daycaca => {
        let node = this.$el.querySelector('input[type="file"]')
        if (node && node.files) {
          Array.from(node.files).forEach(file => {
            if ((this.limit === 0 || this.$$fileCount < this.limit) && this.beforeUpload(file)) {
              this.$$fileCount++
              let reader = new FileReader()
              reader.onload = (e) => {
                let image = new Image()
                image.onload = () => {
                  daycaca.compress(image, self.quality, data => {
                    let headers = store.getHeaders()
                    let formData = new FormData()
                    formData.append('upfile', data)
                    self.uploadProgress()
                    axios.post(self.action, formData, {headers: headers}).then((res) => {
                      self.uploadSuccess(res.data)
                      this.$$fileCount--
                      if (this.$$fileCount) {
                        this.loading = false
                      }
                    })
                  })
                }
                image.src = e.target.result
              }
              reader.readAsDataURL(file)
            }
          })
        }
      })
    },
    beforeUpload (file) {
      let formatReg = new RegExp(this.formatList.join('|'), 'i')
      if (file.size > this.size) {
        console.log(`上传的文件不能超过${this.size / 1024 / 1024}M`)
        return false
      }
      if (!formatReg.test(file.name)) {
        console.log('图片格式格式不正确,请重新上传')
        return false
      }
      if (this.disabled) {
        return false
      }
      return true
    },
    uploadProgress () {
      this.loading = true
    },
    uploadSuccess (res) {
      let url = res.data
      if (res.result === '0') {
        if (this.limit === 1) {
          this.$emit('input', url).$emit('change', res.data).$emit('success', url).$emit('blur')
        } else {
          let value = [...this.value]
          value.push(url)
          this.$emit('input', value).$emit('change', value).$emit('success', value).$emit('blur')
        }
      } else {
        this.$emit('exception', res)
        console.log(res.msg || '文件上传失败')
      }
    }
  }
}
</script>
<style lang="scss">
  .m-img-upload{
    box-sizing:border-box;
    border:1px solid $border-color-base;
    display:inline-block;
    background-size: cover;
    background-repeat: no-repeat;
    width:2rem;
    height:2rem;
    position:relative;
    vertical-align: middle;
    margin-bottom:5px;
    background:rgba(0,0,0,0.05);
    &-icon{
      position:absolute;
      top:50%;
      left:50%;
      text-align:center;
      transform:translate(-50%,-50%);
      font-size:$font-size-small;
      color:rgba(0,0,0,0.4);
      white-space: nowrap;
      .iconfont{
        font-size:0.6rem;
      }
    }
    input[type="file"]{
      height:100%;
      width:100%;
      position:absolute;
      top:0;
      right:0;
      opacity:0;
      z-index:10;
    }
  }
</style>
